/******************************************************************************
 *
 * SD products client with connect timeout only.
 *
 *****************************************************************************/
#include	"unp.h"
#include    "ajay.h"

int
main(int argc, char **argv)
{
	int					sockfd, n;
	char				recvline[MAXLINE + 1];
	struct sockaddr_in	servaddr;
	int 				retval=-1;
	int 				i=0;
	int 				no_of_rdng=10;

	time_t rawtime;
	struct tm *timeinfo;
	//printf ( "Current local time and date: %s", asctime (timeinfo) );

	if (argc != 2)
		err_quit("usage: a.out <IPaddress>");

	if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
		err_sys("socket error");

	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_port   = htons(2000);	/* daytime server */
	if (inet_pton(AF_INET, argv[1], &servaddr.sin_addr) <= 0)
		err_quit("inet_pton error for %s", argv[1]);

	//if (connect(sockfd, (SA *) &servaddr, sizeof(servaddr)) < 0) //regular connect.
	if (connect_timeo(sockfd, (SA *) &servaddr, sizeof(servaddr), 5) < 0) //timeout connect
		err_sys("connect error");

	for(i=0;i<no_of_rdng;i++){
		n = write(sockfd, T_CMD, sizeof(T_CMD));
		if(n!=sizeof(T_CMD)){
			err_sys("write error");
		}

		/* timeout on a read operation */
		retval=Readable_timeo(sockfd,10);
		if(retval==0){
			err_sys("read timeout");
		}else{
			if ( (n = read(sockfd, recvline, MAXLINE)) > 0) {
				time ( &rawtime );
				timeinfo = localtime ( &rawtime );
				strcat(recvline,",");
				strcat(recvline,asctime(timeinfo));
				recvline[n] = '\n';	/* null terminate */
				if (fputs(recvline, stdout) == EOF)
					err_sys("fputs error");
			}
			if (n < 0)
				err_sys("read error");
		}
		sleep(5);
	}

	close(sockfd);
	exit(0);
}

